<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div>
        <a-form layout="inline">
          <a-form-item>
            <a-radio-group v-model="queryParam.statisticsType" style="margin-bottom: 16px">
              <a-radio-button :value="1">
                按月统计
              </a-radio-button>
              <a-radio-button :value="2">
                按季统计
              </a-radio-button>
              <a-radio-button :value="3">
                按年统计
              </a-radio-button>
            </a-radio-group>
          </a-form-item>
          <a-form-item>
            <a-date-picker
              v-model="startTime"
              :disabled-date="disabledStartDate"
              format="YYYY-MM-DD"
              placeholder="开始日期"
              @openChange="handleStartOpenChange"
            />~
            <a-date-picker
              v-model="endTime"
              :disabled-date="disabledEndDate"
              format="YYYY-MM-DD"
              placeholder="结束日期"
              :open="endOpen"
              @openChange="handleEndOpenChange"
            />
          </a-form-item>
          <a-form-item>
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="reloadPage" >查询</a-button>
              <a-button style="margin-left: 8px" @click="resetForm">重置</a-button>
            </span>
          </a-form-item>
        </a-form>
      </div>
    </a-card>
    <a-row>
      <a-card :bordered="false" title="销售业绩统计">
        <v-chart :forceFit="true" :height="height" :data="achievementData" :scale="scale">
          <v-tooltip />
          <v-legend
            :custom="legendCustom"
            :allow-all-canceled="legendAllowAllCanceled"
            :items="legendItems"
            :itemFormatter="achievementitemFormatter"
            :on-click="legendOnClick"
          />
          <v-axis
            data-key="profitAmount"
            :grid="axisGrid"
            :label="axisLabel"
          />
          <v-bar position="code*totalTaxPrice" color="#3182bd" :label="achievemenLabelInterval"/>
          <v-smooth-line position="code*profitAmount" color="#fdae6b" :size="gemoSize" :label="achievemenProfitLabelInterval"/>
          <v-point shape="circle" position="code*profitAmount" color="#fdae6b" :size="gemoSize" />
        </v-chart>
      </a-card>
    </a-row>
    <a-row>
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <a-card :bordered="false" title="VIP客户统计">
          <v-chart :forceFit="true" :height="height" :data="customerData" :scale="scale">
            <v-tooltip :showTitle="false" dataKey="customerName*percent" />
            <v-axis />
            <v-legend dataKey="customerName" />
            <v-pie position="percent" color="customerName" :v-style="pieStyle" :label="labelConfig" />
            <v-coord type="theta" />
          </v-chart>
        </a-card>
      </a-col>
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <a-card :bordered="false" title="热销产品统计">
          <v-chart :forceFit="true" :height="height" :data="hotMaterialData" :scale="scale">
            <v-coord type="rect" direction="LB" />
            <v-tooltip />
            <v-axis dataKey="code" />
            <v-bar position="code*val" :label="hotMaterialLabelInterval"/>
          </v-chart>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>
<script>
import moment from 'moment'
import { statisticsAchievement, statisticsHotMaterial, statisticsCustomer } from '@/api/modular/main/order/sale/saleOrderManage'

const DataSet = require('@antv/data-set')

const scale = [
  {
    dataKey: 'percent',
    min: 0,
    formatter: '.0%'
  },
  {
    dataKey: 'val',
    alias: '销量'
  },
  {
    dataKey: 'totalTaxPrice',
    alias: '销售总额'
  },
  {
    dataKey: 'profitAmount',
    alias: '利润总额'
  }
]

const achievemenLabelInterval = ['totalTaxPrice', {
  textStyle: {
    fill: '#8d8d8d'
  },
  offset: 10,
  formatter: function formatter(text) {
    return '￥' + text.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  }
}]

const achievemenProfitLabelInterval = ['profitAmount', {
  textStyle: {
    fill: 'red'
  },
  offset: 10,
  formatter: function formatter(text) {
    return '￥' + text.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  }
}]

const hotMaterialLabelInterval = ['val', {
  textStyle: {
    fill: '#8d8d8d'
  },
  offset: 10,
  formatter: function formatter(text) {
    return text.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  }
}]

const achievementitemFormatter = val => {
  return val === 'totalTaxPrice' ? '销售总额' : '利润总额'
}

export default {
  components: {
    moment
  },
  data() {
    return {
      // 查询参数
      queryParam: {
        statisticsType: 1
      },
      startTime: null,
      endTime: null,
      endOpen: false,
      achievementData: [],
      scale,
      achievementitemFormatter,
      achievemenLabelInterval,
      achievemenProfitLabelInterval,
      hotMaterialLabelInterval,
      hotMaterialData: [],
      customerData: [],
      height: 400,
      style: { stroke: '#fff', lineWidth: 1 },
      tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
      axisLabel: {
        textStyle: {
          fill: '#fdae6b'
        }
      },
      axisGrid: null,
      gemoSize: 3,
      legendCustom: true,
      legendAllowAllCanceled: true,
      legendItems: [
        { value: 'totalTaxPrice', marker: { symbol: 'square', fill: '#3182bd', radius: 5 } },
        { value: 'profitAmount', marker: { symbol: 'hyphen', stroke: '#fdae6b', radius: 5, lineWidth: 3 } }
      ],
      legendOnClick: (ev, chart) => {
        const item = ev.item
        const value = item.value
        const checked = ev.checked
        const geoms = chart.getAllGeoms()
        for (let i = 0; i < geoms.length; i++) {
          const geom = geoms[i]
          if (geom.getYScale().field === value) {
            if (checked) {
              geom.show()
            } else {
              geom.hide()
            }
          }
        }
      },
      pieStyle: {
        stroke: '#fff',
        lineWidth: 1
      },
      labelConfig: ['percent', {
        formatter: (val, item) => {
          return item.point.customerName + ': ' + val + ' [￥' + item.point.totalTaxPrice + ']'
        }
      }]
    }
  },
  created () {
    this.resetForm()
    this.reloadPage()
  },
  methods: {
    moment,
    getCurrentData() {
      return new Date().toLocaleDateString()
    },
    getFirstDayOfYear () {
      const year = new Date().getFullYear()
      return year + '-' + '01' + '-' + '01'
    },
    reloadPage () {
      if (this.startTime) {
        this.queryParam.searchBeginTime = moment(this.startTime).format('YYYY-MM-DD')
      }
      if (this.endTime) {
        this.queryParam.searchEndTime = moment(this.endTime).format('YYYY-MM-DD')
      }
      this.statisticsAchievement()
      this.statisticsHotMaterial()
      this.statisticsCustomer()
    },
    statisticsAchievement () {
      statisticsAchievement(this.queryParam).then((res) => {
        if (res.success) {
          this.achievementData = res.data
        } else {
          this.$message.error('统计销售业绩失败:' + res.message)
        }
      })
    },
    statisticsHotMaterial () {
      statisticsHotMaterial(this.queryParam).then((res) => {
        if (res.success) {
          var dv = new DataSet.View().source(res.data)
          dv.transform({
            type: 'sort',
            callback(a, b) {
              return a.val - b.val
            }
          })
          this.hotMaterialData = dv.rows
        } else {
          this.$message.error('统计热销产品失败:' + res.message)
        }
      })
    },
    statisticsCustomer () {
      statisticsCustomer(this.queryParam).then((res) => {
        if (res.success) {
          var dv = new DataSet.View().source(res.data)
          dv.transform({
            type: 'percent',
            field: 'percent',
            dimension: 'customerName',
            as: 'percent'
          })
          this.customerData = dv.rows
        } else {
          this.$message.error('统计客户失败:' + res.message)
        }
      })
    },
    disabledStartDate(startTime) {
      const endTime = this.endTime
      if (!startTime || !endTime) {
        return false
      }
      return startTime.valueOf() > endTime.valueOf()
    },
    disabledEndDate(endTime) {
      const startTime = this.startTime
      if (!endTime || !startTime) {
        return false
      }
      return startTime.valueOf() >= endTime.valueOf()
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open
    },
    resetForm () {
      this.startTime = moment(this.getFirstDayOfYear(), 'YYYY-MM-DD')
      this.endTime = moment(this.getCurrentData(), 'YYYY-MM-DD')
    }
  }
}
</script>
